<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
import bwPowerSet from './PowerSet'
// 商品数据
const goods = ref({})
let pathMap = {}
const getGoods = async () => {
  // 1135076  初始化就有无库存的规格
  // 1369155859933827074 更新之后有无库存项（蓝色-20cm-中国）
  const res = await axios.get('http://pcapi-xiaotuxian-front-devtest.itheima.net/goods?id=1369155859933827074')
  goods.value = res.data.result
  // console.log(res.data.result.specs);
  // console.log(res.data.result.skus);
  // console.log(res.data.result);
  pathMap =  getPathMap(goods.value)
  // console.log(pathMap);
  initDisabledStatus(goods.value.specs,pathMap)
}
onMounted(() => getGoods())

// 切换选中状态-》click事件
const ClassActive = (item,val)=>{
  // console.log(item);
  console.log(val.name);
  if(val.disabled) return //disabled=true
    // item：同一排对象
    // val：当前点击项


    // 点击当前的项：1.已经激活的点击后取消激活;
    //  2.如果当前未激活，点击后清除同排与自己的激活的（排他），然后再激活自己
    if(val.selected){
        val.selected = false
    }else{
        item.values.forEach(valItem => valItem.selected = false)
        val.selected = true
    }
    // 点击按钮时更新
    updateDisabledState(goods.value.specs,pathMap)
    // 产出sku对象数据
    const index = getSelectedValues(goods.value.specs).findIndex(item=>item === undefined)
    if(index > -1){
      console.log('找到了，信息不完整');
    }else{
      console.log('信息完整');
      // 获取sku对象
      const key =  getSelectedValues(goods.value.specs).join('-')
      const skuIds = pathMap[key]
      console.log(skuIds);
       // 以skuId作为匹配项去goods.value.skus数组中找
      const skuObj = goods.value.skus.find(item => item.id === skuIds[0])
      console.log('sku对象为', skuObj)
      
    }

}
// 生成有效路径字典对象
const getPathMap = (goods)=>{
  const patMap = {}
  // 1.根据skus字段生成有效的sku数组
  const effectiveSkus = goods.skus.filter(sku=>sku.inventory > 0)
//  console.log(effectiveSkus);
//  console.log(goods.skus);
 // 2.根据有效的sku使用算法（子集算法） [1,2] => [[1],[2],[1,2]]
  effectiveSkus.forEach(sku=>{
    // console.log(sku);
    // 2.1 获取匹配的valueName组成的数组
    const selectedValArr = sku.specs.map(val=>val.valueName)
    // console.log(selectedValArr);
    // 2.2使用算法获取子集
    const valueArrPowerSet = bwPowerSet(selectedValArr)
    // console.log(valueArrPowerSet);
    // 3.把得到的子集生成最终的路径字典对象
    valueArrPowerSet.forEach(arr=>{
      // 准备初始化key 数组join -》 字符串 对象的key
      const key = arr.join('-')
      // 如果已经存在当前key了，就往数组中直接添加skuId 不存在key 直接做赋值
      if(patMap[key]){
        patMap[key].push(sku.id)
      }else{
        patMap[key] = [sku.id]
      }
    })
  })
  return patMap
}

// 初始化禁用状态
const initDisabledStatus = (specs, pathMap)=>{
  // console.log(specs);
  // console.log(pathMap);
  specs.forEach(spec=>{
    spec.values.forEach(val=>{
      if(pathMap[val.name]){
        val.disabled = false
      }else{
        val.disabled = true
      }
    })
  })
}


// 切换时更新禁用状态
const updateDisabledState  = (specs, pathMap)=>{
   // 约定：每一个按钮的状态由自身的disabled进行控制
   specs.forEach((spec,index)=>{
    const selectedValues =  getSelectedValues(specs)
    spec.values.forEach(val=>{
      selectedValues[index] = val.name
      const key = selectedValues.filter(value=>value).join('-')
      if(pathMap[key]){
        val.disabled = false 
      }else{
        val.disabled = true
      }
    })
   })
}

// 获取选中匹配数组 ['黑色',undefined,undefined]
const getSelectedValues = (specs)=>{
  const arr = []
  specs.forEach(spec=>{
    // 找到values中selected为true的项，然后把他的name字段添加到数组对应的位置
    const selectedVal =  spec.values.find(value => value.selected)
    arr.push(selectedVal ? selectedVal.name : undefined)
  })
  // console.log(arr);
  return arr
}
</script>

<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <!-- 图片类型规格 -->
          <!-- val.selected自己添加的项 -->
          <img v-if="val.picture" 
            @click="ClassActive(item,val)"
            :class="{selected:val.selected, disabled:val.disabled}"

            :src="val.picture" 
            :title="val.name">
          <!-- 文字类型规格 -->
          <span v-else
          @click="ClassActive(item,val)"
          :class="{selected:val.selected, disabled:val.disabled}"
          >{{ val.name }}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>

<style scoped lang="scss">
@mixin sku-state-mixin {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;

  &.selected {
    border-color: #27ba9b;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

.goods-sku {
  padding-left: 10px;
  padding-top: 20px;

  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      flex: 1;
      color: #666;

      >img {
        width: 50px;
        height: 50px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }

      >span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }
    }
  }
}
</style>